Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
Vue 3: What's the proper way of handling event listeners like "visibilitychange" and "offline"?

Note A: I'm not talking about event listeners on elements, like @click

Note B: I've been looking "all over" for this but couldn't find it anywhere. Feel free to slap my face if the answer is out there.

Note C: I'm a beginner with Vue trying to learn stuff

I guess I could put those kind of event listeners within main.js, but that just seems a bit off? Also how would I call functions declared within App.vue from main.js?

I'm guessing there's a better and more proper way to handle this within App.vue and the life cycle?

Any help would be greatly appreciated!

Here are two vanilla JS code examples, one with window and one with document:

window.addEventListener('offline', function() {
  alert('You seem to be offline!');
});

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'visible') {
    alert('Hello again!');
  }
});

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can set the event listener in the created or mounted hook in your SFC like this:

<script>
export default {
  created () {
    document.addEventListener('visibilitychange', this.handleVisibility, false)
  },
  methods: {
    handleVisibility (e) {
      if (document.visibilityState === 'hidden') {
        // do what you like
      } else {
        // again do as you like
      }
    }
  }
};
</script>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda